<?php

namespace api\web\controller;

use api\web\model\MoneyModel;
use api\web\model\UserModel;
use api\web\validate\AddressValidate;
use api\web\validate\UserValidate;
use cmf\controller\RestBaseController;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

class UserController extends RestBaseController
{
    public function register()
    {
        // 获取请求数据
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('register')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 检查手机号是否已存在
        if (UserModel::where('mobile', $data['mobile'])->find()) {
            return json(['status' => 'error', 'message' => '手机号已被注册']);
        }

        // 验证短信验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 创建用户
        try {
            $user = UserModel::create($data);
            // 生成 token
            $token = signToken($user->id, $user->mobile); // 确保调用正确的 signToken 函数
            return json(['status' => 'success', 'data' => $user->toArray(), 'token' => $token]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }


    public function login()
    {
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('login')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 获取用户信息
        $user = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return json(['status' => 'error', 'message' => '账号不存在']);
        }

        // 验证验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 生成 token
        $token = signToken($user->id, $user->mobile);
        return json(['status' => 'success', 'data' => ['token' => $token], 'message' => '登录成功']);
    }


    public function sendSms()
    {
        // 手动加载配置文件
        \think\facade\Config::load('E:\phpstudy_pro\WWW\zmt\data\config\app.php', 'app');

        // 读取配置项
        $accessKeyId = config('app.aliSms.accessKeyId');
        $accessKeySecret = config('app.aliSms.accessKeySecret');

        // 验证数据
        $mobile = Request::post('mobile');
        $validate = new UserValidate();
        if (!$validate->scene('sendsms')->check(['mobile' => $mobile])) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 生成验证码
        $code = mt_rand(1000, 9999);

        // 将验证码存储到数据库，有效期5分钟
        Db::name('sms_code_log')->insert([
            'mobile' => $mobile,
            'code' => $code,
            'send_time' => time()
        ]);

        // 发送短信
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => "阿里云短信测试",
            "templateCode" => "SMS_154950909",
            "templateParam" => json_encode(["code" => $code])
        ]);

        try {
            $runtimeOptions = new RuntimeOptions([
                "verify" => false
            ]);
            $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
            return json(['status' => 'success', 'message' => '短信发送成功']);
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return json(['status' => 'error', 'message' => $error->getMessage()]);
        }
    }


    private function checkSmsCode($mobile, $code, $deleteAfterCheck = false)
    {
        // 检查验证码是否正确且未过期
        $smsCodeLog = Db::name('sms_code_log')->where('mobile', $mobile)->order('send_time', 'desc')->find();
        if ($smsCodeLog && $smsCodeLog['code'] == $code && (time() - $smsCodeLog['send_time']) <= 300) {
            if ($deleteAfterCheck) {
                Db::name('sms_code_log')->where('id', $smsCodeLog['id'])->delete();
            }
            return true;
        }
        return false;
    }

    private function createRandStr($length)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randStr = '';
        for ($i = 0; $length > $i; $i++) {
            $randStr .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $randStr;
    }

    //图片上传

    //本地上传
    public function local()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image', $file);
        // 上传到本地服务器
        if ($result) {
            $this->success('upload success', [
                'url' => $result
            ]);
        }
    }

    //七牛云
    public function uploadToQiniu()
    {
        // 使用 thinkphp 提供的方法接收文件，参数名为：file
        $file = request()->file('image');
        if (!$file) {
            halt('请选择文件！');
        }
        // 打印文件信息查看
        // halt($file);

        // 读取对象存储配置
        $accessKey = config('app.qiniuOss.accessKey');
        $secretKey = config('app.qiniuOss.secretKey');
        $bucket = config('app.qiniuOss.bucket');

        // 鉴权
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();

        // 要上传文件的本地路径
        $filePath = $file->getPathname();
        // 上传到存储后保存的文件名（这里使用时间戳作为文件名，严格来说这并不能保证文件名唯一，仅作为示例。）
        $saveName = time(). '.' . $file->getOriginalExtension();
        $uploadMgr = new UploadManager();
        list($return, $error) = $uploadMgr->putFile($token, $saveName, $filePath);
        if ($error !== null) {
            // 获取具体错误信息
            halt($error->message());
        } else {
            // 成功，打印返回值
            halt($return);
        }
    }

    //本地
//    public function uploadImage()
//    {
//        // 获取上传的文件
//        $file = request()->file('image');
//        if (!$file) {
//            return json(['code' => 0, 'msg' => '没有上传文件']);
//        }
//
//        try {
//            // 保存文件到 public/uploads 目录下
//            $filePath = Filesystem::disk('public')->putFile('uploads', $file);
//            if (!$filePath) {
//                return json(['code' => 0, 'msg' => '文件上传失败']);
//            }
//
//            return json(['code' => 1, 'msg' => '文件上传成功', 'data' => ['url' => '/storage/' . $filePath]]);
//        } catch (\Exception $e) {
//            return json(['code' => 0, 'msg' => '文件上传失败: ' . $e->getMessage()]);
//        }
//    }


    //七牛云
//    public function uploadImage()
//    {
//        // 获取上传的文件
//        $file = Request::file('image');
//        $mobile = Request::post('mobile'); // 获取手机号
//
//        if (!$file) {
//            return json(['status' => 'error', 'message' => '没有上传文件']);
//        }
//
//        if (!$mobile) {
//            return json(['status' => 'error', 'message' => '手机号不能为空']);
//        }
//
//        // 验证文件
//        $validate = new \think\Validate([
//            'image' => 'fileExt:jpg,png,gif,jpeg|fileSize:10485760', // 允许的扩展名和文件大小
//        ]);
//        $data = ['image' => $file];
//        if (!$validate->check($data)) {
//            return json(['status' => 'error', 'message' => $validate->getError()]);
//        }
//
//        // 七牛云配置
//        $accessKey = 'Ok7K9Wu7Sh4LHWsVY0VIfGuO0gtQWCIhAsUU3u-c';
//        $secretKey = 'QGBna_SWDhcj_tS1DFUqahFevRWXZIwEofDyPN0s';
//        $bucket = 'zmtapp';
//        $domain = 'sej8bq1b7.hb-bkt.clouddn.com'; // 七牛云的外链域名
//
//        // 获取文件信息
//        $filePath = $file->getRealPath();
//        $fileName = uniqid() . '.' . $file->extension(); // 生成唯一文件名
//
//        // 构建鉴权对象
//        $auth = new Auth($accessKey, $secretKey);
//
//        // 生成上传Token
//        $token = $auth->uploadToken($bucket);
//
//        // 初始化UploadManager
//        $uploadMgr = new UploadManager();
//
//        // 上传文件到七牛云
//        list($ret, $err) = $uploadMgr->putFile($token, $fileName, $filePath);
//
//        if ($err !== null) {
//            return json(['status' => 'error', 'message' => $err->message()]);
//        } else {
//            // 生成文件URL
//            $fileUrl = $domain . '/' . $ret['key'];
//
//            // 更新数据库记录
//            Db::name('user')->where('mobile', $mobile)->update(['image' => $fileUrl]);
//
//            return json(['status' => 'success', 'url' => $fileUrl, 'message' => '头像上传成功']);
//        }
//    }

    //查询个人信息

    public function getUserInfo()
    {
        $header = request()->header();
        if(!isset($header['token'])|| empty($header['token'])){
            $this -> error('缺少 token');
        }
        $key = new Key(config( 'app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($header['token'],$key);
        }catch(Exception $exception){
            $this->error($exception->getMessage());
        }
        $userInfo = UserModel::field(  'id,image,name,mobile')
            ->where('id',$res->data->user_id)
            ->find();
        $userInfo['image']=request()->domain() . '/storage/' . $userInfo['image'];
        $this->success( '用户信息', $userInfo);
    }

        //修改个人信息
    public function updateInfo()
    {

        $header = request()->header();
        if(!isset($header['token'])|| empty($header['token'])){
            $this -> error('缺少 token');
        }
        $key = new Key(config( 'app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($header['token'],$key);
        }catch(Exception $exception){
            $this->error($exception->getMessage());
        }

        $data = input('post.');
        //验证
        $user = UserModel::find($res->data->user_id);
        $user->image = $data['image'];
        $user->name = $data['name'];
        $user->mobile = $data['mobile'];
        if($user->save()){
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }

    public function getAddress()
    {
        $token = Request::header();
        if (!isset($token['token']) || empty($token['token'])) {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'), 'HS256');

        try {
            $res = JWT::decode($token['token'], $key);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $page = input('page/d', 1);
        $pageSize = input('page_size/d', 10);
        $list = UserModel::field('mobile,address,name,location')
            ->order('id', 'desc')
            ->where('mobile', '=', $res->data->mobile)
            ->page($page, $pageSize)
            ->select();

        $this->success('收货信息列表', $list);
    }

    public function addAddress()
    {
        // 获取请求数据
        $data = input();
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['create_time'] = date('Y:m:d H:i:s');
        $add = UserModel::create($data);
        if($add){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    // 新增的修改收货地址的方法
    public function updateAddress()
    {
        $data = input();
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['update_time'] = date('Y:m:d H:i:s');
        $edit = UserModel::where('id','=',$data['id'])
            ->update($data);
        if($edit){
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }

    //充值功能
    public function addMoney()
    {
        $data = input('post.');

        // 获取 userId 通过中间件设置
        $user_id = request()->userId;

        // 验证输入数据
        $validate = new UserValidate();
        if (!$validate->scene('addMoney')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()], 400);
        }

        // 获取充值金额
        $money = $data['money'];
        $reason = $data['reason'] ?? '充值';

        //开启事务
        Db::startTrans();
        try {
            // 记录流水
            $newBalance = add_money_log($user_id, $money, $reason, 1);
            Db::commit();
            return json(['status' => 'success', 'message' => '充值成功', 'new_balance' => $newBalance]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    // 查询流水记录
    public function getTransactionLogs()
    {
        // 获取 userId 通过中间件设置
        $user_id = request()->userId;

        try {
            // 查询流水
            $logs = get_transaction_logs($user_id);

            return json(['status' => 'success', 'logs' => $logs]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
}
